package org.rich.charlesmurphy.ui;


import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

import org.ddevil.data.BasicData;
import org.rich.charlesmurphy.core.DataLoader;
import org.rich.charlesmurphy.core.DataLoaderCommand;
import org.rich.charlesmurphy.core.InputFileType;
import org.rich.charlesmurphy.model.CharlieMurphyModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.windowkit.toolkit.Worker;
import org.windowkit.toolkit.Worker.WorkListener;
import org.windowkit.toolkit.frame.Desktop;
import org.windowkit.toolkit.frame.GlassPane;
import org.windowkit.toolkit.frame.WindowGroup;
import org.windowkit.toolkit.frame.WindowLauncher;
import org.windowkit.toolkit.frame.GlassPane.LoadingPane;
import org.windowkit.toolkit.panel.AbstractPanel;


/**
 * The main UI for this thang.
 * @author Rich O'Connell
 */
public class View extends JFrame {
	private static final long serialVersionUID = -3566788299365358655L;

	private static final String TITLE = "Charlie Murphy's HTPP Session Viewer";

	private Logger log = LoggerFactory.getLogger(getClass());

	private Desktop desktop;
	private DataLoader dataLoader;
	private InputFileType defaultFileType = InputFileType.CHARLES;
	private GlassPane glassPane;
	private Executor executor = Executors.newSingleThreadExecutor();

	public View() {
		super(TITLE);
		JPanel contentPane = new JPanel();
		contentPane.setLayout(new BorderLayout());
		setContentPane(contentPane);

		glassPane = new GlassPane();
		glassPane.addCenterComponent(new LoadingPane());

		desktop = new Desktop();
		contentPane.add(desktop, BorderLayout.CENTER);
		desktop.setBackground(Colors.DESKTOP);

        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setSize(1200,700);
        setVisible(true);

        JMenu file = new JMenu("File");
        file.add(new JMenuItem(actLoadFile));

        JMenuBar menu = new JMenuBar();
        menu.add(file);
        contentPane.add(menu, BorderLayout.NORTH);
	}

	private Component oldGlassPane;
	protected void toggleGlassPane(boolean visible) {
		if (visible) {
			oldGlassPane = getGlassPane();
			setGlassPane(glassPane);
			glassPane.setVisible(true);
		}
		else {
			if (oldGlassPane != null) {
				setGlassPane(oldGlassPane);
			}
			glassPane.setVisible(false);
		}
	}

	/**
	 * Load a new data set from the file(s).
	 * @param file the input file
	 * @param type the type of file, determines the parsing
	 * @param host host name, optional. If specified all requests from other hosts
	 * @param filterAjax filter ajax requests
	 * will be filtered out.
	 */
	public void loadData(final DataLoaderCommand command) {
		defaultFileType = command.getFileType();
		
		WorkListener listener = new WorkListener() {
			public void workComplete(Worker worker) {
				CharlieMurphyModel model = (CharlieMurphyModel)worker.getResults().getValue("results");
				dataLoadComplete(model);
				toggleGlassPane(false);
			}
		};


		toggleGlassPane(true);
		executor.execute(new Worker(listener) {
			@Override
			protected void doWork() {
				CharlieMurphyModel model = dataLoader.loadData(command);
				model.setSessionName(command.getSessionName());
				setResults(new BasicData());
				getResults().setDataItem("results", model);
			}
		});


	}

	/**
	 * called after a data load has been processed.
	 */
	protected void dataLoadComplete(CharlieMurphyModel model) {
		final ControlPanel controlPanel = new ControlPanel(model);
		final WindowGroup wg = desktop.launchWindow(controlPanel);

		WindowLauncher wl = new WindowLauncher() {
			public void launchWindow(AbstractPanel view) {
				((AbstractCharliePanel)view).setControlPanel(controlPanel);
				view.setLauncher(this);
				desktop.launchWindow(wg, view);
			}
		};
		controlPanel.setLauncher(wl);

		wl.launchWindow(new ViewByPage(model, wl));
	}


	private void showLoadFile() {
		CharliesFileChooser fc = new CharliesFileChooser(defaultFileType);
		
		fc.setMultiSelectionEnabled(true);
		fc.setDialogTitle("Load...");
		if(fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){
			DataLoaderCommand cmd = fc.makeCommand();
			if (cmd.getFiles().length > 0) {
				loadData(cmd);
			}
		}
	}

	private Action actLoadFile = new AbstractAction("Load...") {
		private static final long serialVersionUID = 1480519962552397859L;
		public void actionPerformed(ActionEvent e) {
			showLoadFile();
		}
	};

	/**
	 * @param dataLoader the dataLoader to set
	 */
	public void setDataLoader(DataLoader dataLoader) {
		this.dataLoader = dataLoader;
	}

}
